package com.jason.platform.supervision.activity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.hzlj.supervision.changsha.R;
import com.jason.platform.supervision.adapter.DailySignDetailAdapter;
import com.jason.platform.supervision.base.Constant;
import com.jason.platform.supervision.beans.SignBean;
import com.jason.platform.supervision.beans.SignResp;
import com.jason.platform.supervision.task.QuerySignDetailTask;
import com.jason.platform.supervision.task.Task;
import com.jason.platform.supervision.task.TaskListener;
import com.jason.platform.supervision.utils.DateUtils;
import com.jason.platform.supervision.widght.LoadingDialog;
import com.jason.platform.supervision.widght.TitleBar;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @ClassName: DailySignDetailActivity
 * @Description: 日常签到详情
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-7-25 09:47:20
 */
public class DailySignDetailActivity extends BaseActivity implements View.OnClickListener, TaskListener {

    private static final String TAG = DailySignDetailActivity.class.getSimpleName();

    public static final String KEY_SIGN = "key_sign";

    //准备对话框Id
    private static final int DATE_BEGIN_DIALOG_ID = 0;
    private static final int DATE_END_DIALOG_ID = 1;

    private TitleBar mTitleBar;

    private MyHandler<DailySignDetailActivity> mHandler;
    private View mFootView;

    //搜索

    private TextView mBeginTextView, mEndTextView;
    private Button mSearchButton;

    private ListView mListView;
    private DailySignDetailAdapter mAdapter;
    private List<SignBean> mSignBeans = new ArrayList<SignBean>();

    private String mBeginDate;
    private String mEndDate;

    private int mYear, mMonth, mDay;

    private int mDateDialogType = DATE_BEGIN_DIALOG_ID;
    private SignBean mSignBean;
    private String mSignId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_daily_sign_detail);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        mSignBean = (SignBean) getIntent().getSerializableExtra(KEY_SIGN);
        if (mSignBean != null) {
            Log.i(TAG, mSignBean.toString());
            mSignId = String.valueOf(mSignBean.getId());
        }
        mHandler = new MyHandler<DailySignDetailActivity>(this);
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTitleBar.bindActivity(this);
        initSearchView();
        mListView = (ListView) findViewById(R.id.daily_sign_detail_list);
        mAdapter = new DailySignDetailAdapter(this);
        if (mFootView == null) {
            mFootView = LinearLayout.inflate(this, R.layout.widget_listview_footer, null);
        }
        mFootView.setVisibility(View.GONE);
        mListView.addFooterView(mFootView);
        mListView.setAdapter(mAdapter);

        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (view.getLastVisiblePosition() == (view.getCount() - 1)) {//滚动到底部
                        if (!mIsLoading && mHasNextPage) {
                            loadMore();
                        } else {
                            if (mFootView != null) {
                                mFootView.setVisibility(View.GONE);
                            }
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        initDate();
        getSearchValue();
        mIsLoading = true;
        mIsStart = true;
        mCurrentIndex = 0;
        QuerySignDetailTask task = new QuerySignDetailTask(this);
        task.type = Constant.Sign.QUERY_SIGN_DETAIL;
        task.mParams.put("currentIndex", String.valueOf(++mCurrentIndex));//页码
        task.mParams.put("id", mSignId);//日常签到ID
        task.mParams.put("timeBegin", mBeginDate);//开始时间
        task.mParams.put("timeEnd", mEndDate);//结束时间
        task.execute();
    }

    private void initDate() {
        //得到当前日期
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
    }

    @Override
    protected void initLoadingDialog() {
        super.initLoadingDialog();
        mLoadingDialog = new LoadingDialog(this);
        mLoadingDialog.setIsOut(false);
        mLoadingDialog.setMessage("加载中");
    }

    private void initSearchView() {
        mBeginTextView = (TextView) findViewById(R.id.daily_sign_detail_begin);
        mEndTextView = (TextView) findViewById(R.id.daily_sign_detail_end);
        mSearchButton = (Button) findViewById(R.id.daily_sign_detail_search);
        mBeginTextView.setOnClickListener(this);
        mEndTextView.setOnClickListener(this);
        mSearchButton.setOnClickListener(this);
        mBeginTextView.setText(DateUtils.converDatLongToString(System.currentTimeMillis(), DateUtils.DATE_YMD));
        mEndTextView.setText(DateUtils.converDatLongToString(System.currentTimeMillis(), DateUtils.DATE_YMD));
    }

    private void getSearchValue() {
        mBeginDate = mBeginTextView.getText().toString();
        mEndDate = mEndTextView.getText().toString();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.daily_sign_detail_search) {
            //TODO 调用接口，进行搜索
            mLoadingDialog.show();
            initData();
        } else if (v.getId() == R.id.daily_sign_detail_begin) {
            mDateDialogType = DATE_BEGIN_DIALOG_ID;
            showDialog(DATE_BEGIN_DIALOG_ID);
        } else if (v.getId() == R.id.daily_sign_detail_end) {
            mDateDialogType = DATE_END_DIALOG_ID;
            showDialog(DATE_END_DIALOG_ID);
        }
    }

    //准备日期设置监听器
    private DatePickerDialog.OnDateSetListener dsl = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            String month = String.valueOf(mMonth + 1);
            String day = String.valueOf(mDay);
            if (month.length() == 1) {
                month = "0" + month;
            }
            if (day.length() == 1) {
                day = "0" + day;
            }

            if (mDateDialogType == DATE_BEGIN_DIALOG_ID) {

                mBeginTextView.setText(mYear + "-" + month + "-" + day);
            } else if (mDateDialogType == DATE_END_DIALOG_ID) {
                mEndTextView.setText(mYear + "-" + month + "-" + day);
            }
        }
    };

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        if (id == DATE_BEGIN_DIALOG_ID) {
            //把Activity上下文、日期设置监听器、以及日期的年月日都作为参数传给那个新成立的对话框组件
            return new DatePickerDialog(this, dsl, mYear, mMonth, mDay);
        } else if (id == DATE_END_DIALOG_ID) {
            //把Activity上下文、日期设置监听器、以及日期的年月日都作为参数传给那个新成立的对话框组件
            return new DatePickerDialog(this, dsl, mYear, mMonth, mDay);
        }
        return null;
    }

    private void loadMore() {
        if (mFootView == null) {
            mFootView = LinearLayout.inflate(this, R.layout.widget_listview_footer, null);
        }
        mFootView.setVisibility(View.VISIBLE);
        mListView.setSelection((mListView.getAdapter().getCount() - 1));
        mIsLoading = true;
        mIsStart = false;
        getSearchValue();
        QuerySignDetailTask task = new QuerySignDetailTask(this);
        task.type = Constant.Sign.QUERY_SIGN_DETAIL;
        task.mParams.put("currentIndex", String.valueOf(++mCurrentIndex));//页码
        task.mParams.put("id", mSignId);//日常签到ID
        task.mParams.put("timeBegin", mBeginDate);//开始时间
        task.mParams.put("timeEnd", mEndDate);//结束时间
        task.execute();
    }

    @Override
    public void onTaskResult(Task task) {
        Message msg = new Message();
        msg.obj = task;
        mHandler.sendMessage(msg);
    }

    @Override
    void handleMessage(BaseActivity activity, Message msg) {
        Task task = (Task) msg.obj;
        if (task.type == Constant.Sign.QUERY_SIGN_DETAIL) {
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
            }
            if (task.isSuccess) {
                SignResp resp = (SignResp) task.resData;
                if (mIsStart) {
                    mSignBeans.clear();
                }
                mSignBeans.addAll(resp.getValues());
                if (mSignBeans != null && !mSignBeans.isEmpty()) {
                    if (mAdapter != null) {
                        mAdapter.addAll(mSignBeans);
                        mAdapter.notifyDataSetChanged();
                    }
                }
                mHasNextPage = !resp.isLastPage();
                mIsLoading = false;
                if (mHasNextPage) {
                    if (mFootView != null) {
                        mFootView.setVisibility(View.VISIBLE);
                    }
                } else {
                    if (mFootView != null) {
                        mFootView.setVisibility(View.GONE);
                    }
                }
            } else {
                if (mAdapter != null) {
                    mAdapter.addAll(new ArrayList<SignBean>());
                    mAdapter.notifyDataSetChanged();
                }
                if (mFootView != null) {
                    mFootView.setVisibility(View.GONE);
                }
                Toast.makeText(this, task.rspDesc, Toast.LENGTH_SHORT).show();
            }
        }
    }
}
